﻿using King.Box.Utils.Global;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using Newtonsoft.Json.Linq;
using System.Timers;

namespace King.Box.Cache
{
    public class TokenCacheService
    {
        private static string _token = null;

        private Timer _providerTimer;

        public TokenCacheService()
        {
            _providerTimer = new Timer(60 * 1000 * GlobalConfig.TokenCacheMinute);
            _providerTimer.Elapsed += new ElapsedEventHandler(Clear);
            _providerTimer.AutoReset = true;
            _providerTimer.Enabled = true;
        }

        public static string GetToken()
        {
            if (string.IsNullOrEmpty(_token))
                _token = GetTokenApi();

            return _token;
        }

        private static string GetTokenApi()
        {
            var clientId = GlobalConfig.ClientId;
            var clientSecret = GlobalConfig.ClientSecret;

            var parameters = new Dictionary<string, string>();
            parameters.Add("grant_type", "client_credentials");

            var _httpClient = new HttpClient();
            _httpClient.BaseAddress = new Uri(GlobalConfig.ApiAddress);
            _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
                "Basic", Convert.ToBase64String(Encoding.ASCII.GetBytes(clientId + ":" + clientSecret)));

            var response = _httpClient.PostAsync("/token", new FormUrlEncodedContent(parameters)).Result;
            var responseValue = response.Content.ReadAsStringAsync();
            if (response.StatusCode == System.Net.HttpStatusCode.OK)
                return JObject.Parse(responseValue.Result)["access_token"].Value<string>();
            else
                return string.Empty;
        }

        private void Clear(object source, ElapsedEventArgs e)
        {
            _token = null;
        }
    }
}
